package com.hzn.home_with_tabs;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.ArrayList;

/**
 * Created by hzn on 14-11-25.
 */
public abstract class PagesAdapter extends FragmentPagerAdapter implements IconAdapter{
    ArrayList<Page> mPages;

    public static class Page {
        public Page(Fragment fragment, int icon, String title) {
            mFragment = fragment;
            mIcon = icon;
            mTitle = title;
        }

        public Fragment mFragment;
        public int mIcon;
        public String mTitle;
    }

    public PagesAdapter(FragmentActivity activity) {
        super(activity.getSupportFragmentManager());
        mPages = new ArrayList<Page>();

        addPages();
    }

    /**
     *　使用addPage()　增加页面
     */
    public abstract void addPages();

    protected void addPage(Class<? extends Fragment> fragment_class, int icon, String title) {
        try {
            Fragment fragment = fragment_class.newInstance();
            Page page = new Page(fragment, icon, title);
            mPages.add(page);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Fragment getItem(int position) {
        Page page = mPages.get(position);
        if (page != null) {
            return page.mFragment;
        }

        throw new UnsupportedOperationException("no page with this position.");
    }

    @Override
    public int getIcon(int position) {
        Page page = mPages.get(position);
        if (page != null) {
            return page.mIcon;
        }

        throw new UnsupportedOperationException("no page with this position.");
    }

    @Override
    public int getCount() {
        return mPages.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Page page = mPages.get(position);
        if (page != null) {
            return page.mTitle;
        }

        return super.getPageTitle(position);
    }
}
